package com.iapp.aop;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.log4j.Log4j2;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;

/**
 * @author wrh
 * description:LogAspect打印接口信息相关
 */
@Aspect
@Component
@Log4j2
public class LogAspect {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Pointcut("execution(public * com.iapp.controller.*.*(..))")
    public void logPointCut() {
    }

    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) throws Throwable {
        // 接收到请求，记录请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();
        log.info("\n");
        log.info("****请求**** {}", sdf.format(new Date()));
        log.info("请求地址 : {} 接口名称 : {} 请求参数 : {}", request.getRemoteAddr(), request.getRequestURL().toString(), Arrays.toString(joinPoint.getArgs()));
        // 记录下请求内容
//        log.info("请求token ：" + request.getHeader("token"));
//        log.info("HTTP METHOD : " + request.getMethod());
//        log.info("接口名称 : " + request.getRequestURL().toString());
//        log.info("请求参数 : " + Arrays.toString(joinPoint.getArgs()));

//        log.info("请求地址 : " + request.getRemoteAddr() + " 接口名称 : " + request.getRequestURL().toString() + " 请求参数 : " + Arrays.toString(joinPoint.getArgs()));

    }

    @AfterReturning(returning = "ret", pointcut = "logPointCut()")
    /**returning的值和doAfterReturning的参数名一致*/
    public void doAfterReturning(Object ret) throws Throwable {
        // 处理完请求，返回内容
        log.info("****返回****");
        log.info("返回值 : {}", JSONObject.toJSONString(ret));
        // log.info("返回值 : " + ret);
    }

    @Around("logPointCut()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        long startTime = System.currentTimeMillis();
        Object ob = pjp.proceed();
        // ob 为方法的返回值
        log.info("耗时 : {}", (System.currentTimeMillis() - startTime));
        return ob;
    }
}
